﻿using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SignalrClientTest
{
    /// <summary>
    /// signalr客户端的一些操作
    /// </summary>
    public class SignalrOperation
    {
        /// <summary>
        /// 一个signalr连接可以有很多个Proxy
        /// </summary>
        public HubConnection conn;
        /// <summary>
        /// 绑定回调事件，以及调用服务器中相应的Hub中的方法（和Hub一一对应）
        /// </summary>
        public IHubProxy MsgProxy;


        public SignalrOperation(string serverurl, string proxyName, IDictionary<string, string> headers)
        {
            ServerUrl = serverurl;
            ProxyName = proxyName;
            Headers = headers;
        }

        /// <summary>
        /// 连接到服务器
        /// </summary>
        /// <returns></returns>
        public void LinkServer()
        {
            conn = new HubConnection(ServerUrl, false);
            conn.TransportConnectTimeout = new TimeSpan(0, 0, 5);//客户端断开连接时间
            ServicePointManager.DefaultConnectionLimit = 1;//限制并发数量

            foreach (var item in Headers)
            {
                conn.Headers.Add(item.Key, item.Value);
            }

            conn.StateChanged += Connection_StateChanged;
            MsgProxy = conn.CreateHubProxy(ProxyName);

            //绑定三个方法
            MsgProxy.On<string>("Receive", (message) => AddReceiveMsg(message));
            MsgProxy.On<string>("MsgReceive", (message) => AddReceiveMsg(message));
            MsgProxy.On("Error", exception => AddReceiveMsg(exception));

            conn.Start();
        }

        /// <summary>
        /// 接收消息的方法
        /// </summary>
        /// <param name="message"></param>
        public virtual void AddReceiveMsg(string message)
        {

        }

        /// <summary>
        /// 实现在UI中各种调用,客户端应该是直接使用HubConnection这个索引
        /// </summary>
        /// <param name="obj"></param>
        public virtual void Connection_StateChanged(StateChange obj)
        {

        }

        private string ProxyName;
        private string ServerUrl { get; set; }
        private IDictionary<string, string> Headers { get; set; }
    }
}
